package com.sjr.easy.chat.app.controller;

import com.alibaba.fastjson2.JSON;
import com.github.stuxuhai.jpinyin.PinyinException;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import com.google.common.collect.Lists;
import com.sjr.easy.chat.app.dto.AppTokenInfo;
import com.sjr.easy.chat.app.utils.AppTokenManager;
import com.sjr.easy.chat.dto.Result;
import com.sjr.easy.chat.model.Contact;
import com.sjr.easy.chat.model.User;
import com.sjr.easy.chat.service.ContactService;
import com.sjr.easy.chat.service.UserService;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
public class AppContactController {

    @Autowired
    private ContactService contactService;

    @Autowired
    private UserService userService;

    @Autowired
    private AppTokenManager appTokenManager;

    @Data
    @ApiModel("通讯录展示列表项")
    static class GetContactsListItem {
        @ApiModelProperty("用户id")
        private Long id;

        @ApiModelProperty("用户编号")
        private String code;

        @ApiModelProperty("昵称")
        private String nickname;

        @ApiModelProperty("昵称拼音")
        private String nicknamePy;

        @ApiModelProperty("昵称拼音")
        private String nicknamePyPrefixLetter;

        @ApiModelProperty("用户头像")
        private String headPortrait;

        @ApiModelProperty("用户头像存储类型：http存储类型可以直接加载、local类型需要通过指定接口加载图片")
        private String headPortraitStoreType;
    }

    @ApiOperation("查询联系人列表")
    @GetMapping("/app/contact/getContactsList")
    public Result<List<GetContactsListItem>> getContactsList() {

        AppTokenInfo appTokenInfo = appTokenManager.getTokenInfo();
        List<Contact> contactList = contactService.selectContactsListByUserId(appTokenInfo.getId());
        List<Long> userIdList = ListUtils.emptyIfNull(contactList).stream().map(Contact::getContactUserId).toList();
        List<User> userList = userService.selectByIdList(userIdList);

        List<GetContactsListItem> getContactsListItemList = ListUtils.emptyIfNull(userList).stream().map(user -> {
            GetContactsListItem getContactsListItem = new GetContactsListItem();
            BeanUtils.copyProperties(user, getContactsListItem);
            try {
                String nicknamePy = PinyinHelper.getShortPinyin(user.getNickname());
                getContactsListItem.setNicknamePy(nicknamePy);
                getContactsListItem.setNicknamePyPrefixLetter(nicknamePy.substring(0, 1).toUpperCase());
            } catch (PinyinException e) {
                log.error("ex:", e);
                getContactsListItem.setNicknamePy("#");
            }
            return getContactsListItem;
        }).toList();

        return Result.success(getContactsListItemList);
    }

    @ApiOperation("校验userCode对应用户是否为当前用户联系人")
    @GetMapping("/app/contact/checkIsContact")
    public Result<Boolean> checkIsContact(@RequestParam Long userId) {
        log.info("userId:{}", userId);
        AppTokenInfo tokenInfo = appTokenManager.getTokenInfo();
        Contact contact = contactService.getContact(tokenInfo.getId(), userId);
        if (contact == null) {
            return Result.success(false);
        }
        return Result.success(true);
    }

    @Data
    static class GetContactsInfoReqParams {
        @ApiModelProperty("联系人用户ID")
        Long contactsUserId;
    }

    @Data
    static class GetContactsUserInfoResultData {
        @ApiModelProperty("用户id")
        private Long id;

        @ApiModelProperty("用户编号")
        private String code;

        @ApiModelProperty("昵称")
        private String nickname;

        @ApiModelProperty("用户头像")
        private String headPortrait;

        @ApiModelProperty("用户头像存储类型：http存储类型可以直接加载、local类型需要通过指定接口加载图片")
        private String headPortraitStoreType;
    }

    @ApiOperation("查询联系人信息")
    @GetMapping("/app/contact/getContactsUserInfo")
    public Result<Object> getContactsUserInfo(GetContactsInfoReqParams reqParams) {
        log.info("reqParams:{}", JSON.toJSONString(reqParams));
        GetContactsUserInfoResultData resultData = new GetContactsUserInfoResultData();

        AppTokenInfo appTokenInfo = appTokenManager.getTokenInfo();
        Contact contact = contactService.getContact(appTokenInfo.getId(), reqParams.contactsUserId);
        User user = userService.selectById(contact.getContactUserId());
        BeanUtils.copyProperties(user, resultData);

        return Result.success(resultData);
    }

    @Data
    static class DeleteContactsReqParams {
        @ApiModelProperty("联系人ID")
        Long contactsUserId;
    }

    @ApiOperation("删除联系人")
    @PostMapping("/app/contact/deleteContact")
    public Result<Object> deleteContacts(@RequestBody DeleteContactsReqParams reqParams) {

        log.info("reqParams:{}", JSON.toJSONString(reqParams));
        AppTokenInfo tokenInfo = appTokenManager.getTokenInfo();

        Long selfUserId = tokenInfo.getId();
        Long contactsUserId = reqParams.getContactsUserId();
        Contact contact1 = contactService.getContact(selfUserId, contactsUserId);
        Contact contact2 = contactService.getContact(contactsUserId, selfUserId);

        contactService.deleteByIdList(Lists.newArrayList(contact1.getId(), contact2.getId()));
        return Result.success();
    }
}
